package com.zhkj.txg.module.mine.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.BaseResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.module.mine.entity.CollectionListResponse
import com.zhkj.txg.module.mine.model.MineManager
import com.zhkj.txg.module.mine.ui.CollectStatusChangeEvent
import io.reactivex.android.schedulers.AndroidSchedulers

class CollectionViewModel(application: Application) : BaseViewModel(application) {
    private val mineManager = MineManager()
    private val checkStatusChangeLiveData = MutableLiveData<CollectStatusChangeEvent>()
    val collectionLiveData = MutableLiveData<HttpResponse<CollectionListResponse>>()
    val cancelCollectionLiveData = MutableLiveData<HttpResponse<BaseResponse>>()
    val editMode = MutableLiveData<Boolean>()

    private val numb = 20
    var page = 1
        private set

    var type: String = ""

    fun collectionList(token: String, shopId:String,restart: Boolean = false) {
        val listener =
            object : ViewModelSubscribeListener<CollectionListResponse>(collectionLiveData) {
                override fun onSuccess(resp: CollectionListResponse) {
                    resp.hasMore = resp.data.size >= numb
                    resp.loadMore = page > 1
                    super.onSuccess(resp)
                    page += 1
                }
            }
        if (restart) page = 1
        val collectionList = mineManager.collectionList(token, shopId,page, numb, type, listener)
        dispose.add(collectionList)
    }

    fun cancelCollection(token: String, collectionIds: String) {
        val listener = ViewModelSubscribeListener(cancelCollectionLiveData)
        val cancelCollection = mineManager.cancelCollection(token, collectionIds, type, listener)
        dispose.add(cancelCollection)
    }

    fun checkStatusChangeSubscribe(): MutableLiveData<CollectStatusChangeEvent> {
        val subscribe = RxBus.toObservable(CollectStatusChangeEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ checkStatusChangeLiveData.value = it }, { it.printStackTrace() })
        dispose.add(subscribe)
        return checkStatusChangeLiveData
    }
}